package com.woniu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.entity.Cart;
import com.woniu.entity.Product;
import com.woniu.entity.User;
import com.woniu.mapper.CartMapper;
import com.woniu.mapper.ProductMapper;
import com.woniu.service.CartService;
import com.woniu.vo.CartItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author huangjianbin
 * @since 2023-02-07 11:59:17
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Autowired
    CartMapper cartMapper;

    @Autowired
    ProductMapper productMapper;

    @Override
    public void addProductToCart(Integer productId, Integer userId) {

        Product product = productMapper.selectById(productId);

        //将商品加入购物车
        //1.先查看购物车中是否已经有了该商品
//        QueryWrapper<Cart> productQueryWrapper = new QueryWrapper<>();
//        productQueryWrapper.eq("product_id",productId);
//        productQueryWrapper.and
        Cart cart = cartMapper.queryByProductIdAndUserId(productId, userId);
        if (cart==null){
            //尚未加购过  //如果还没有加购过,那就写入一条新的数据
            Cart newItem = new Cart();
            newItem.setProductId(productId);
            newItem.setBuycount(1);
            newItem.setUserId(userId);

//            Product product = productMapper.selectById(productId);
            newItem.setSumprice(product.getProductprice());

            cartMapper.insert(newItem);

        }else{
            //已经加购过  //如果已经加购过,则更新购买量和小计
            cart.setBuycount(cart.getBuycount()+1);
            cart.setSumprice(cart.getSumprice().add(product.getProductprice()));

            cartMapper.updateById(cart);
        }
    }

    @Override
    public List<CartItemVo> queryAll(Integer id) {
        ArrayList<CartItemVo> cartItemVoArrayList = new ArrayList<>();
        
        //1.查询到当前用户的所有购物项
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.eq("user_id", id);

        List<Cart> cartList = cartMapper.selectList(cartQueryWrapper);

//        2.将 cartList 转为 cartItemVoArrayList
        for (Cart cart : cartList) {

            CartItemVo cartItemVo = new CartItemVo();
            cartItemVo.setCartItemId(cart.getId());
            cartItemVo.setProductId(cart.getProductId());

            Product product = productMapper.selectById(cart.getProductId());
            cartItemVo.setProductName(product.getProductname());
            cartItemVo.setProductPrice(product.getProductprice());
            cartItemVo.setProductImgsrc(product.getProductimgsrc());

            cartItemVo.setBuycount(cart.getBuycount());
            cartItemVo.setSumprice(cart.getSumprice());

            cartItemVoArrayList.add(cartItemVo);
            
        }
        return cartItemVoArrayList;
    }

    @Override
    public void updatebuycount(Integer id, Integer productId, Integer changeNum) {
        Cart cart = cartMapper.queryByProductIdAndUserId(productId, id);
        Product product = productMapper.selectById(productId);
        if (cart==null){
            throw new RuntimeException("参数非法");
        }
        if (changeNum==1){
            cart.setBuycount(cart.getBuycount()+1);
            cart.setSumprice(cart.getSumprice().add(product.getProductprice()));
            cartMapper.updateById(cart);
        } else if (changeNum==-1){
            cart.setBuycount(cart.getBuycount()-1);
            if (cart.getBuycount()==0){
                cartMapper.deleteById(cart.getId());
            }else{
                cart.setSumprice(cart.getSumprice().subtract(product.getProductprice()));
                cartMapper.updateById(cart);
            }
        } else {
            cartMapper.deleteById(cart.getId());
        }
    }

    @Override
    public BigDecimal calculateTotalPrice(Integer id, Integer[] productIds) {
        //查询出所有被选择的购物项
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.eq("user_id",id);
//        cartQueryWrapper.and(new Consumer<QueryWrapper<Cart>>() {
//            @Override
//            public void accept(QueryWrapper<Cart> cartQueryWrapper) {
//                cartQueryWrapper.in("product_id",productIds);
//            }
//        });
        cartQueryWrapper.and(cartQueryWrapper1 -> cartQueryWrapper1.in("product_id",productIds));

        List<Cart> carts = cartMapper.selectList(cartQueryWrapper);

        //写法1: for循环
        //计算总价
        BigDecimal totalPrice = new BigDecimal("0.00");
        for(Cart cart : carts){
            totalPrice = totalPrice.add(cart.getSumprice());
        }

        //写法2: stream + lambda
//        BigDecimal totalPrice = carts.stream()
//                .map(new Function<Cart, BigDecimal>() {
//                    @Override
//                    public BigDecimal apply(Cart cart) {
//                        return cart.getSumprice();
//                    }
//                })
//                .reduce(BigDecimal.ZERO, BigDecimal::add);
        //或者
//       BigDecimal totalPrice = carts.stream()
//                    .map(Cart::getSumprice)
//                    .reduce(BigDecimal.ZERO, BigDecimal::add);


        return totalPrice;
    }


}
